import { Form, Input, Modal, Select, Space, Tooltip, Typography } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { FC, forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { FactoryMap } from '@/typings/global';
import { addRotateConfig, getFactoryMap, hasRotateConfig } from '@/api/rotate-config-page';
import './index.less';
import { MessageError } from '@/utils/tool';
const { TextArea } = Input;

interface OnSettingProps {
  success: () => void;
}

export interface ISettingModelRef {
  handleEvent: (type: string, record?) => void;
}

const OnSetting = (props, ref) => {
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [isCreate, setIsCreate] = useState<boolean>(true);
  const [type, setType] = useState<string>('');
  const [factoryMapList, setFactoryMapList] = useState<Array<FactoryMap>>();
  const [factoryListOptions, setFactoryListOptions] = useState<Array<Record<string, string>>>();
  const [productLineListOptions, setProductLineListOptions] = useState<Array<Record<string, string>>>();

  // 使用Form.useForm定义form
  const [form] = Form.useForm();
  const rules = [
    {
      required: true,
      message: '该字段不能为空！'
    }
  ];

  const offsetRule = [
    ...rules,
    {
      pattern: /^-?\d+(\.\d{1,3})?$/, // 正则表达式（有正负）
      message: '请输入数字，并且小数点后最多输入三位'
    }
  ];

  useEffect(() => {
    getFactoryMapList();
  }, []);

  const getFactoryMapList = async () => {
    const res = await getFactoryMap();
    const factoryMapList = res.data;
    setFactoryMapList(factoryMapList);
    const factoryList = factoryMapList.map(item => {
      return { value: item.factory, label: item.factory };
    });
    setFactoryListOptions(factoryList);
    const productLineList = factoryMapList[0].productLine.map(item => {
      return { value: item, label: item };
    });
    setProductLineListOptions(productLineList);
  };

  const handleOk = async () => {
    try {
      // 手动调用表单校验
      await form.validateFields();
      const data = form.getFieldsValue();
      data.offsetX = parseFloat(data.offsetX);
      data.offsetY = parseFloat(data.offsetY);
      if (type == 'add') {
        const flag = await hasRotateConfig({ factory: data.factory, productLine: data.productLine });
        if (flag.data) {
          // 如果是新增且对应的厂区产线已经存在数据，则不能通过新增按钮来，而是要通过找到对应厂区的产线的设置按钮来
          MessageError('新增的厂区产线配置已存在，如需修改请点击对应厂区产线的设置按钮！');
          return;
        }
      }
      setIsOpen(false);
      //无论修改还是新增都是添加数据
      const params = {
        factory: data.factory?.trim(),
        productLine: data.productLine?.trim(),
        isReverse: Number(data.isReverse),
        angle: Number(data.angle),
        offsetX: parseFloat(data.offsetX),
        offsetY: parseFloat(data.offsetY),
        desc: data.desc
      };
      await addRotateConfig(params);
      props.success();
    } catch (error) {
      console.log('校验失败，错误信息:', error);
    }
  };

  const handleCancel = () => {
    setIsOpen(false);
  };

  const handleEvent = (type, record?) => {
    setIsOpen(true);
    setType(type);
    if (type === 'add') {
      setIsCreate(true);
      form.setFieldsValue({
        factory: null,
        productLine: null,
        isReverse: 0,
        angle: 0,
        offsetX: 0,
        offsetY: 0,
        desc: null
      });
    } else {
      setIsCreate(false);
      if (record.factory) {
        const productLineList = factoryMapList?.filter(item => item.factory === record.factory)[0].productLine as string[];
        const productLineListFormat = productLineList.map(item => {
          return { value: item, label: item };
        });
        setProductLineListOptions(productLineListFormat);
      }
      form.setFieldsValue({
        factory: record.factory,
        productLine: record.productLine,
        isReverse: record.isReverse,
        angle: record.angle,
        offsetX: record.offsetX,
        offsetY: record.offsetY,
        desc: record.desc
      });
    }
  };

  //厂区表单项发生变化时也更新产线的数据
  const onFactoryChange = factory => {
    const productLineList = factoryMapList?.filter(item => item.factory === factory)[0].productLine as string[];
    const productLineListFormat = productLineList.map(item => {
      return { value: item, label: item };
    });
    setProductLineListOptions(productLineListFormat);
    form.setFieldsValue({ productLine: productLineList[0] });
  };

  useImperativeHandle(ref, () => ({
    handleEvent
  }));

  return (
    <div>
      <Modal title="旋转配置" open={isOpen} onOk={handleOk} onCancel={handleCancel} className="set_dialog">
        <Form className="form" labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} layout="horizontal" form={form}>
          <Form.Item label="厂区：" name="factory" rules={rules}>
            <Select options={factoryListOptions} disabled={!isCreate} showSearch={false} onChange={onFactoryChange}></Select>
          </Form.Item>
          <Form.Item label="产线：" name="productLine" rules={rules}>
            <Select options={productLineListOptions} disabled={!isCreate}></Select>
          </Form.Item>
          <Form.Item label="是否X镜像翻转: " name="isReverse" className="item_1" rules={rules}>
            <Select>
              <Select.Option value={1}>是</Select.Option>
              <Select.Option value={0}>否</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="顺时针旋转角度：" name="angle" className="item_2" rules={rules}>
            <Select>
              <Select.Option value={0}>0°</Select.Option>
              <Select.Option value={90}>90°</Select.Option>
              <Select.Option value={180}>180°</Select.Option>
              <Select.Option value={270}>270°</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="X偏移值(mm): " labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} style={{ height: '32px' }} rules={rules} required>
            <Form.Item name="offsetX" className="item_content" rules={offsetRule}>
              <Input type="number" />
            </Form.Item>
            <Form.Item className="item_content_tag">
              <div title="偏贴后面板坐标基于POL膜边0点的X轴方向偏移">
                <QuestionCircleOutlined className="icon" />
              </div>
            </Form.Item>
          </Form.Item>
          <Form.Item label="Y偏移值(mm): " labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} style={{ height: '32px' }} rules={rules} required>
            <Form.Item name="offsetY" className="item_content" rules={offsetRule}>
              <Input type="number" />
            </Form.Item>
            <Form.Item className="item_content_tag">
              <div title="偏贴后面板坐标基于POL膜边0点的Y轴方向偏移">
                <QuestionCircleOutlined className="icon" />
              </div>
            </Form.Item>
          </Form.Item>
          <Form.Item label="备注：" name="desc">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default forwardRef<ISettingModelRef, OnSettingProps>(OnSetting);
